package org.medusa.jsr223;

import javax.script.CompiledScript;
import javax.script.Invocable;
import javax.script.ScriptContext;
import javax.script.ScriptException;
import javax.script.SimpleScriptContext;

public class Jsr223Context {
	private Jsr223Engine engine;
	private Invocable inv;
	private ScriptContext context = new SimpleScriptContext();
	private CompiledScript script;
	
	public Jsr223Context(Jsr223Engine engine, String script_file_path_name) {
		this.engine = engine;
		this.inv = (Invocable) this.engine;
		this.script = this.engine.ReadScriptFile(script_file_path_name);
	}
	/*
	public ScriptEngine GetScriptEngine() {
		return this.engine;
	}*/
	
	public void Run() {
		try {
			this.script.eval(this.context);
		} catch (ScriptException e1) {
			e1.printStackTrace();
		}
	}
	/*
	public void Eval(CompiledScript script) {
		try {
			script.eval(this.context);
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}*/
	
	/*
	public void IntoContext() {
		this.engine.setContext(this.context);
	}
	
	public void LeaveContext() {
		this.engine.setContext(ScriptManager.GetInstance().GetGlobalContext());
	}*/
	
	public Object CallFunction(String fnname, Object... args) {
		Object result=null;
		this.engine.SetContext(this.context);
		
		try {
			result = this.inv.invokeFunction(fnname, args);
		} catch (ScriptException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		}
		
		this.engine.SetContext(this.engine.GetGlobalContext());
		
		return result;
	}
	
	public void SetAttribute(String attr_name, Object value) {
		this.context.setAttribute(attr_name, value, ScriptContext.ENGINE_SCOPE);
	}
	
}
